package cn.wenxin_zhang.smart4j.plus.proxy;

import net.sf.cglib.proxy.MethodProxy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.framework.proxy.ProxyChain;

import java.lang.reflect.Method;
import java.sql.SQLException;

/**
 * Created by Wenxin on 2017/3/10.
 */
public abstract class LifeCycleAspectAdapter extends LifeCycleAspect {

    private static Logger logger = LoggerFactory.getLogger(LifeCycleAspect.class);

    public LifeCycleAspectAdapter() {
    }

    @Override
    public Object doProxy(ProxyChain proxyChain) throws Throwable {
        Object result = null;
        Class<?> cls = proxyChain.getTargetClass();
        Method method = proxyChain.getTargetMethod();
        Object[] params = proxyChain.getMethodParams();
        if (intercept(cls, method, params)) {
            begin(cls, method, params);
            try {
                before(cls, method, params);
                result = proxyChain.doProxyChain();
                afterReturn(cls, method, params, result);
            } catch (Exception e) {
                logger.error("proxy failure:", e);
                error(cls, method, params, e);
            } finally {
                after(cls, method, params);
                end(cls, method, params);
            }
        } else
            result = proxyChain.doProxyChain();
        return result;
    }

    @Override
    protected void begin(Class<?> targetClass, Method method, Object[] params) {

    }

    @Override
    protected void before(Class<?> targetClass, Method method, Object[] params) {

    }

    @Override
    protected boolean intercept(Class<?> cls, Method method, Object[] params) throws Throwable {
        return true;
    }

    @Override
    protected void error(Class<?> targetClass, Method method, Object[] params, Exception e) throws Exception {
    }

    @Override
    protected void afterReturn(Class<?> targetClass, Method method, Object[] params, Object result) {

    }

    @Override
    protected void after(Class<?> targetClass, Method method, Object[] params) throws Exception {

    }

    @Override
    protected void end(Class<?> targetClass, Method method, Object[] params) throws Exception {

    }
}
